using System;
using System.Collections.Generic;
using System.Text;

using Weazel.Microblaze.Simulator.Engine;

namespace Weazel.Microblaze.Simulator.Components.Microblaze.Instructions
{
    public class Lbui : MemoryAccessInstruction
    {

        public override int CycleCount
        {
            get { return 1; }
        }

        public Lbui()
            : base("lbui")
        {
        }

        /// <summary>
        /// Loads a byte (8 bits) from the memory location that results from adding 
        /// the contents of register rA with the value in IMM, sign-extended to 32 
        /// bits. The data is placed in the least significant byte of register rD 
        /// and the other three bytes in rD are cleared.
        /// </summary>    
        public override void Execute(MicroblazeComponent MicroblazeComponent)
        {

            uint address =
              MicroblazeComponent.ReadRegister(SourceRegisterA) +
              GetImmediateValue(MicroblazeComponent);

            ReadWordTransaction transaction = new ReadWordTransaction(MicroblazeComponent, address);
            MicroblazeComponent.BeginDataTransaction(transaction);

            while (transaction.Status != Transaction.TransactionStatus.Complete)
                MicroblazeComponent.WaitOneCycle();

            /*
            // read from memory
            uint memory;
            MemoryAccessStatus status = MicroblazeComponent.DataMemorySpace.ReadWord(address, out memory);


            if (status == MemoryAccessStatus.Ok)
            {
                memory >>= 24;

                // store in register
                MicroblazeComponent.WriteRegister(DestinationRegister, memory, Address);
            }
             * */

            MicroblazeComponent.WriteRegister(DestinationRegister, transaction.Value >> 24, Address);
            
        }

        public override string ToString()
        {
            return string.Format("lbui r{0}, r{1}, r{2}",
              DestinationRegister,
              SourceRegisterA,
              SourceRegisterB
            );
        }
    }
}
